package com.mst.core;

import com.alibaba.fastjson2.JSONObject;
import com.mst.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author 马松涛
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("请求之前");
//        response.setContentType("application/json;charset=utf-8");
//        response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(Result.error(401, "请先登录")));
            return false;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            HasUserName hasUserName = method.getAnnotation(HasUserName.class);
            if (hasUserName != null) {
                if (user.getUsername().equals(hasUserName.value())) {
                    return true;
                } else {
                    response.setContentType("text/html;charset=utf-8");
                    response.getWriter().write(JSONObject.toJSONString(Result.error(403, "没有权限")));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("请求成功之后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("请求已经完成,不管成功还是失败");
    }
}
